﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Entities;
using System.Web;
using Totoro.Core;
using Totoro.Passport;

using Totoro.ORMapping;
using NHibernate;  
using NHibernate.Criterion;

namespace Bussiness
{
    /// <summary>
    /// 授权
    /// </summary>
    public static class Permission
    {
        private static bool _isAuthenticated;

        /// <summary>
        /// 是否已经授权 
        /// </summary>
        public static bool IsAuthenticated { get { return _isAuthenticated; } }

        private static User _currentUser = null;
        /// <summary>
        /// 当前登录用户
        /// </summary>
        public static User CurrentUser { get { return (User)HttpContext.Current.Session["CurrentUser"]; } }

        public static bool CheckIsUserExits(string name)
        { 
              ISession session = NHHelper.GetCurrentSession();
            ICriteria cr = session.CreateCriteria<User>();
            cr.Add(Expression.Eq("LogonName", name));
            IList<User> lst = cr.List<User>();
            
            if (lst.Count > 0) return true;
            else return false; 
        }
        public static Ticket CheckPermission(string name, string password)
        {
            ISession session = NHHelper.GetCurrentSession();
            ICriteria cr = session.CreateCriteria<User>();
            cr.Add(Expression.Eq("LogonName", name));
            //return CreateNewTicket("", name);
            IList<User> lst = cr.List<User>();
            User u;
            if (lst.Count > 0)
            {
                u = lst[0];
                //验证密码 
                if (u.PassWord == Totoro.Core.Cryption.EnCryption(password)){
                    HttpContext.Current.Session["CurrentUser"] = u;
                    return CreateNewTicket(u.ID, u.LogonName);
                }
                else return null; 
            }
            else return null;


        }
        public static bool CheckCookiePermission()
        {
            HttpCookie c = HttpContext.Current.Request.Cookies["tt_ticket"];
            if (c == null) return false;
            string str = c.Value;
            Ticket t = Ticket.GetTicketFromStr(str);
            if (t.IsValid())
            {
                
                HttpContext.Current.Response.SetCookie(new HttpCookie("tt_ticket", t.SerializeTicketToStr()));
                _isAuthenticated = true; 
                return true;
            }
            else return false; 
        }
        public static Ticket CreateNewTicket(string userID, string userName)
        {
            string ip = HttpContext.Current.Request.UserHostAddress;
            return new Ticket(ip, userName, userID);
        }

        public static void Logon(string name, string password) { }

        public static void Logout(string name, string password) { }

    }
}
